#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  Storage_Blob_Manager.py
#  description

#  Created by zhouzongli633 on 2020/5/27 9:48 上午.
#  Copyright ©Intellectus All rights reserved.

import os
from datetime import datetime, timedelta

from azure.storage.blob import BlobServiceClient
from azure.storage.blob import BlobServiceClient
from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas
from azure.storage.blob import ContentSettings
from Common.logger import app_log

from NICU2HOME import settings


class StorageManage(object):
    url = "https://{}.blob.core.windows.net".format(
        os.getenv("AZURE_STORAGE_ACCOUNT_NAME")
    )

    connection_string = settings.STORAGE_CONNECT_STR

    def upload_file(self, file_data, file_name, content_type='image/png'):
        try:
            blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

            blob_client = blob_service_client.get_blob_client(
                container=settings.STORAGE_CONTAINER_NAME,
                blob=file_name,
            )
            blob_client.upload_blob(
                data=file_data,
                content_settings=ContentSettings(content_type=content_type)
            )
            app_log.info("上传完成:{}".format(file_name))
            return
        except Exception as e:
            print(e)

    def delete_file(self, file_name):
        try:
            blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

            blob_client = blob_service_client.get_blob_client(
                container=settings.STORAGE_CONTAINER_NAME,
                blob=file_name,
            )

            blob_client.delete_blob(
                delete_snapshots='include'
            ),

            app_log.info("删除完成:{}".format(file_name))
        except Exception as e:
            print(e)

    def get_shared_access_signature(self):
        # Instantiate a BlobServiceClient using a connection string
        blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)

        # Create a SAS token to use to authenticate a new client
        sas_token = generate_account_sas(
            blob_service_client.account_name,
            account_key=blob_service_client.credential.account_key,
            resource_types=ResourceTypes(object=True),
            permission=AccountSasPermissions(read=True, create=True, write=True),
            expiry=datetime.utcnow() + timedelta(hours=1)
        )
        return sas_token


if __name__ == '__main__':
    manager = StorageManage()
    sas_t = manager.get_shared_access_signature()
    print(sas_t)
